package com.youkeda.test.http;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageAsker {

    public static void main(String[] args) {
        String url = "http://photo.yupoo.com/vibius/GkRSowXr/medish.jpg";
        ImageAsker asker = new ImageAsker();
        byte[] data = asker.getContent(url);

        try {
            File file = new File("medish.jpg");
            FileOutputStream outputStream = new FileOutputStream(file);
            outputStream.write(data, 0, data.length);
            System.out.println("下载成功");
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据输入的url，读取页面内容并返回
     */
    public byte[] getContent(String url) {
        String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.835.163 Safari/535.1";
        // okHttpClient 实例
        OkHttpClient okHttpClient = new OkHttpClient();
        // 定义一个request
        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", userAgent)
                .addHeader("Refer", "http://photo.yupoo.com")
                .addHeader("Host", "photo.yupoo.com")
                .build();
        byte[] bytes = new byte[0];
        try {
            // 执行请求
            Response response = okHttpClient.newCall(request).execute();
            bytes = response.body().bytes();
        } catch (IOException e) {
            System.out.println("request " + url + " error . ");
            e.printStackTrace();
        }

        return bytes;
    }
}
